import { Controller } from 'egg';

import { Result } from '../util';
import { uuidCommonRule } from './validate-rule';

class WorkUnitController extends Controller {
  async show() {
    const { ctx } = this;

    ctx.validate({
      uuid: uuidCommonRule
    }, ctx.query);

    const { uuid } = ctx.query;

    const tableData = await ctx
      .service
      .workUnit
      .findListByUuid(
        uuid
      );

    ctx.body = new Result({ tableData });
  }

  async delete() {
    const { ctx } = this;

    ctx.validate({
      uuid: uuidCommonRule,
      questionnaireUuid: uuidCommonRule
    }, ctx.request.body);

    const { uuid, questionnaireUuid } = ctx.request.body;

    const result = await ctx
      .service
      .workUnit
      .delete(uuid, questionnaireUuid);

    if (!result) {
      ctx.body = new Result({ result }, '删除成功！因为已经没有其他选项，所以已为您隐藏了对应题目！');
      return;
    }

    ctx.body = new Result({ result }, '删除成功！');
  }

  async create() {
    const { ctx } = this;

    ctx.validate({
      questionnaireUuid: uuidCommonRule,
      name: {
        type: 'string',
        max: 100
      }
    }, ctx.request.body);

    const { questionnaireUuid, name } = ctx.request.body;

    const result = await ctx.service.workUnit.create(
      questionnaireUuid, name
    );
    if (!result) {
      ctx.status = 422;
      ctx.body = new Result(result, '工作单位已存在！');
      return;
    }
    ctx.body = new Result(result, '添加成功');
  }
}

module.exports = WorkUnitController;
